package tjs.study.notes.eureka.clienta.user.service.feign.log;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class DefaultWebMvcConfig implements WebMvcConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(DefaultWebMvcConfig.class);

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //日志链路追踪拦截器
        registry.addInterceptor(new TraceInterceptor()).addPathPatterns("/**");
    }


    static class TraceInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            String traceId = request.getHeader(CommonConstant.LOG_TRACE_ID);
            if (StringUtils.isNotEmpty(traceId)) {
                MDC.put(CommonConstant.LOG_TRACE_ID, traceId);
            }
            CommonConstant.TL.set(traceId);
            logger.info("traceId：" + traceId);
            return true;
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            MDC.remove(CommonConstant.LOG_TRACE_ID);
        }
    }

}
